//
//  CZOAuthViewController.swift
//  weibo
//
//  Created by 丁蒙 on 16/6/26.
//  Copyright © 2016年 丁蒙. All rights reserved.
//

import UIKit
import SVProgressHUD

class CZOAuthViewController: UIViewController {
    
    override func loadView() {
        
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // MARK - 设置导航栏
        self.title = "OAuth登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(CZOAuthViewController.cancelButtonClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(CZOAuthViewController.autoButtonClick))
        
        view.backgroundColor = UIColor.whiteColor()
    }
    //MARK - 导航栏按钮点击事件
    func cancelButtonClick() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    func autoButtonClick() {
        let JSString = "document.getElementById('userId').value='lemonding@126.com',document.getElementById('passwd').value='minemine'"
        webView.stringByEvaluatingJavaScriptFromString(JSString)
    }
    
    // MARK - 懒加载webView
    private lazy var webView: UIWebView = {
        
        let web = UIWebView()
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")!
        let request = NSURLRequest(URL: url)
        web.loadRequest(request)
        //
        web.delegate = self
        return web
    }()
    
}
// MARK - WebView代理方法
extension CZOAuthViewController:UIWebViewDelegate {
    //将要开始加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString
        
        if let u = urlString where u.hasPrefix(REDIRECT_URI) {
            
            let query = request.URL?.query
            
            if let q = query {
                
                let code = q.substringFromIndex("code=".endIndex)
                
                loadUserAccount(code)
            }
            
        }
        return true
    }
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //加载结束
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    
}

extension CZOAuthViewController {
    
    func loadUserAccount(code: String) {
        CZNetWorkTools.sharedTools.oauthLoadUserAccount(code, success: { (response) in
            guard let result = response as? [String: AnyObject] else {
                return
            }

            let userAccount = CZUserAcount(dict: result)
            
            self.loadUserAccountInfo(userAccount)
            
            }) { (error) in
                print(error)
        }
    }
    func loadUserAccountInfo(userAccount: CZUserAcount) {
        CZNetWorkTools.sharedTools.oauthLoadUserInfo(userAccount, success: { (response) in
            
            guard let res = response as? [String: AnyObject] else {
                return
            }
            
            userAccount.avatar_large = res["avatar_large"] as? String
            userAccount.screen_name = res["screen_name"] as? String
            
            CZUserAccountTools.sharedUserAccountTools.saveUserAccount(userAccount)
            
            //发送通知 切换到Welcome控制器
            NSNotificationCenter.defaultCenter().postNotificationName(switchNotice, object: "wel")
            
            }) { (error) in
                print(error)
        }
    }
}